﻿using KAsFrame.Common.Application;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace KAsFrame.Common.ServiceExtentisons
{
    public static class ServiceRegisterExtensions
    {
        public static void AddAppServices(this IServiceCollection services)
        {

            // 获取运行目录下所有程序集
            var path = AppDomain.CurrentDomain.BaseDirectory;
            string[] dllFiles = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);

            var assemblies = new List<Assembly>();
            foreach (var item in dllFiles)
            {
                assemblies.Add(Assembly.LoadFrom(item));
            }
            services.ServiceRegister(assemblies.ToArray());
        }

        public static void ServiceRegister(this IServiceCollection services, params Assembly[] assemblies)
        {
            if (assemblies.Length <= 0)
            {
                return;
            }
            foreach (var assembly in assemblies)
            {

                var allTypes = assembly.GetTypes().Where(x => x.IsClass && !x.IsAbstract).ToList();

                foreach (var type in allTypes.FindAll(x => typeof(ITransientDependency).IsAssignableFrom(x)))
                {
                    //  获取当前实现类的接口，但不包含我们的标记类
                    var interfaceTypes = type.GetInterfaces().Where(p => !p.FullName.Contains("ITransientDependency"));
                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddTransient(interfaceType, type);
                    }
                }

                foreach (var type in allTypes.FindAll(x => typeof(ISingletonDependency).IsAssignableFrom(x)))
                {
                    //  获取当前实现类的接口，但不包含我们的标记类
                    var interfaceTypes = type.GetInterfaces().Where(p => !p.FullName.Contains("ISingletonDependency"));
                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddSingleton(interfaceType, type);
                    }
                }

                foreach (var type in allTypes.FindAll(x => typeof(IScopedDependency).IsAssignableFrom(x)))
                {
                    //  获取当前实现类的接口，但不包含我们的标记类
                    var interfaceTypes = type.GetInterfaces().Where(p => !p.FullName.Contains("IScopedDependency"));
                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddScoped(interfaceType, type);
                    }
                }
            }

        }
    }
}
